<?php
/**
 * Files.php
 *
 * @author  :  Skiychan <dev@skiy.net>
 * @link    :  http://www.zzzzy.com
 * @created :  2015/12/12
 * @modified:
 * @version :  0.0.1
 */

require(APPPATH.'libraries/Web_Controller.php');
class Files extends Web_Controller {
    private $_user_info = null;  //用户信息
    private $_limit = array(); //翻页

    public function __construct() {
        parent::__construct();

        $services = array(
            'login_service',
            'user_files_service'
        );
        $this->load->service($services);
        $this->_user_info = $this->login_service->get_user_info();
    }

    /**
     * 获取文件夹&&文件列表
     */
    public function list_get() {
        #$state 0：表示所有文件，1：已分享，2已下载，3已过期
        $state = (int)$this->input->get('state', true);

        #判断类型
        if(! in_array($state,array(0,1,2)))
            return $this->common_response(1003);

        #获取文件夹ID
        $page = intval($this->input->get('page', true));
        $total = trim($this->input->get('total', true));
        $total = empty($total) ? 20 : $total;
        $this->_limit = $total > 0 ? array($page * $total, $total) : array();

        //全部文件、文件夹
        if ($state === 0) {
            #文件夹id
            $folder_id = intval($this->input->get('pid', true));

            $list = $this->user_files_service->get_list($this->_user_info['id'], $folder_id, "", "creation_ts", "desc", array("deleted" => 0), "", $this->_limit);
            $folders = (array)$list['folders'];
            //给文件夹添加属性
            $folder_tmp = array();
            foreach ($folders as $key => $value) {
                $value['size'] = "0";
                $value['ext_name'] = "0";
                $folder_tmp[] = $value;
            }
            //存在文件夹则将临时变更为正式
            if (count($folder_tmp) > 0) {
                $folders = $folder_tmp;
            }
            #文件夹和文件合并
            $files = array_merge($folders, (array)$list['files']);

            $folder_info = $folder_id > 0 ? $this->user_files_service->get_path_info($this->_user_info['id'], $folder_id) :
                array(
                    "id" => "0",
                    "name" => "/",
                    "path" => "",
                    "path_id" => null,
                    "path_name" => null
                );

            $result = array('data' => $files,"path_info"=>$folder_info);

        //已分享
        } else {
            $file_list = $this->__file_state($state);
            $result = array('data' => (array)$file_list['rows']);
        }

        return $this->common_response(0, '', $result);
    }

    /**
     * 创建文件夹
     */
    public function folder_post() {
        $pid = (int)$this->post("pid");
        $name = trim($this->post("name"));

        $pid = $pid < 0 ? 0 : $pid;
        if (($name !== '0') && empty($name))
            return $this->common_response(1003);

        $resp = $this->user_files_service->add_folder($this->_user_info['id'], $name, $pid);
        if (empty($resp))
            return $this->common_response($this->user_files_service);

        return $this->common_response(0, '', array('data' => $resp));
    }

    /**
     * 获取文件/文件夹详情
     */
    public function detail_get() {
        $type = (int)$this->get('type');
        $id = (int)$this->get('id');

        if (empty($id) || !in_array($type, array(0,1)))
            return $this->common_response(1003);

        $info = $this->user_files_service->get_detail($this->_user_info['id'], $type, $id);
        if (empty($info))
            return $this->common_response($this->user_files_service);

        $this->load->service('user_policies_service');

        $result = array(
            'id'            => (int)$info['id'],
            'name'          => $info['name'],
            'ext_name'      => isset($info['ext_name']) ? $info['ext_name'] : "",
            'description'   => $info['description'],
            'type'          => $type,
            'count'         => $type == 1 ? $this->user_files_service->get_folder_file_count($this->_user_info['id'], $id) : 0,
            'size'          => $type == 1 ? 0 : (int)$info['size'],
            'open'          => $info['access_denied'] == 1 ? 0 : 1
        );

        if (empty($info['data'])) {
            $policy = array(
                'life_span'             => "",
                'delete_after_expired'  => null,
                'open_counter'          => null,
                'password'              => ""
            );
        } else {
            $policy_arr = $this->user_policies_service->policy_to_arr($info['data']);
            $policy = array(
                'life_span'             => !empty($policy_arr['life_span']) ? $policy_arr['life_span'] : "",
                'delete_after_expired'  => isset($policy_arr['delete_after_expired']) ? (int)$policy_arr['delete_after_expired'] : null,
                'open_counter'          =>  isset($policy_arr['open_counter']) ? $policy_arr['open_counter'] : null,
                'password'              => isset($policy_arr['read_pwd']) ? $policy_arr['read_pwd'] : ""
            );
        }

        $result['policy'] = $policy;
        return $this->common_response(0, '', array('data' => $result));
    }

    /**
     * 获取源文件
     */
    public function source_get() {
        $id = $this->get('id');
        if (empty($id))
            return $this->common_response(1003);

        $resp = $this->user_files_service->download_source($this->_user_info['id'], $id);
        if (empty($resp))
            return $this->common_response($this->user_files_service);

        $data = array(
            'url' => Common::source_link(array('id' => $resp))
        );
        return $this->common_response(0, "", array('data' => $data));
    }

    /**
     * 更新文件受限开关
     */
    public function access_control_put() {
        $file_id = trim($this->put('id'));
        $denied = (int)$this->put('denied'); //受限开关, 0为不受限, 1为受限
        $type = (int)$this->put("type"); //0文件,1文件夹

        if (empty($file_id))
            return $this->common_response(1003);

        $files = $folders = '';
        #全局开关
        $all = false;
        if ($type == 1) {
            $folders = explode(",",$file_id);
        } else {
            $files = explode(",",$file_id);
        }

        $edit = $this->user_files_service->update_access_denied($this->_user_info['id'], $files, $folders, $denied, $all);
        if (empty($edit))
            return $this->common_response($this->user_files_service);

        return $this->common_response(0);
    }

    /**
     * 文件或文件夹删除
     */
    public function files_delete() {
        $files = trim($this->delete('files'));
        $folders = trim($this->delete('folders'));
        if (empty($files) && empty($folders))
            return $this->common_response(1003);

        $files = empty($files) ? array() : explode(',', $files);
        $folders = empty($folders) ? array() : explode(',', $folders);

        $this->user_files_service->delete($this->_user_info['id'], $files, $folders);
        return $this->common_response(0);
    }

    /**
     * 获取打包进度
     */
    public function packet_percent_get() {
        $id = $this->get('id');
        if (empty($id))
            return $this->common_response(1003);

        $sess_data = $this->session->userdata("PACKET_LIST");
        if(ENVIRONMENT=="development") {
            if(empty($sess_data) || !is_array($sess_data))
                $sess_data=array();

            $data = array();
            $step = 20;

            if (empty($id)) {
                return $this->common_response(1003);
            } else if (!isset($sess_data[$id]) || !isset($sess_data[$id]['percent'])) {
                return $this->common_response(1003);
            } else if ($sess_data[$id]['percent'] >= 100 || $sess_data[$id]['percent'] + 20 >= 100) {
                $dpercent = 100;
                $params = $sess_data[$id]['params'];
                $data = $this->user_files_service->add_file($params['uid'],$params['name'],$params['size'],$params['mime_type'],$params['md5'],$params['source_guid'],$params['folder_id'],$params['guid']);

                if (empty($data))
                    return $this->common_response($this->user_files_service);

                $add_sec = $this->user_files_service->add_secure_file($data['id'],$params['size'],1,Common::uniqid(),Common::uniqid(),Common::uniqid());
                if (empty($add_sec))
                    return $this->common_response($this->user_files_service);

                $default_path = $this->config->item("default_upload_path")."file/";
                if (! is_dir($default_path))
                    @mkdir($default_path,0777,true);

                $save_path = $default_path.$params['source_guid'].".tmp";

                if ($data['source_guid'] == $params['source_guid'])
                    copy($params['file_path'],$save_path);

                if (file_exists($params['file_path']))
                    @unlink($params['file_path']);

                unset($sess_data[$id]);
            } else {
                $sess_data[$id]['percent'] += $step;
                $dpercent = $sess_data[$id]['percent'];
            }

            $this->session->set_userdata("PACKET_LIST",$sess_data);

            $result = array(
                "id"      =>$id,
                "percent" =>$dpercent,
                "data"    =>$data
            );

        } else {
            $redis = new Redis();
            $con = $redis->connect($this->config->item("host","redis"), $this->config->item("port","redis"), $this->config->item("timeout","redis"));
            if(! $con)
            return $this->common_response(1019);

            $redis_data =  $redis->get($id);
            $data = json_decode($redis_data, true);
            if(! $data)
                return $this->common_response(1019);

            if(! empty($data['error_code']))
                return $this->common_response($data['error_code']);

            $result = array(
                "id"      =>$id,
                "percent" =>$data['percent'],
                "data"    =>$data['data']
            );
        }

        return $this->common_response(0, "", $result);
    }

    /**
     * 获取 1：已分享，2已下载，3已过期
     * @param string $p_type 类型
     */
    private function __file_state($p_type="") {
        switch ($p_type) {
            case 1:
                $files = $this->user_files_service->get_share_file_list($this->_user_info['id'], false, "", "creation_ts", "desc",array("deleted"=>0),"",$this->_limit);

                break;

            case 2:
                $files = $this->user_files_service->get_downloaded_file_list($this->_user_info['id'], false, "", "creation_ts", "desc",array("deleted"=>0),"",$this->_limit);

                break;

            case 3:
                $files = $this->user_files_service->get_exp_file_list($this->_user_info['id'], false, "", "creation_ts", "desc",array("deleted"=>0),"",$this->_limit);

                break;

            default:
                return $this->common_response(1003);
        }

        if (empty($files['rows']))
            return $this->common_response(1003);

        return $files;
    }

    /**
	 * 获取新建文件夹可用序号
	 */
	public function new_folder_num_get() {
		$folder_id = (int)$this->input->get("file_id",TRUE);
		$folders = $this->user_files_service->get_folder_list($this->_user_info['id'],$folder_id,"","name","asc","name");
		//var_dump($folders);exit;
		if(empty($folders))
		{
			$num = 0;
		}
		else
		{
			$num = $this->user_files_service->get_new_folder_num(Common::array_column($folders['rows'],"name"));
		}
		$this->common_response(0,'',array("data"=>array("defindMax"=>$num)));
		//common::prf_json ( , array("defindMax" =>$num));
	}
}